package com.itheima.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.domain.Permission;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;
    @Override
    public Map<String, Object> findById(Integer id) {
        List<Permission> permissionList =  permissionDao.findAll();
        List<Integer> permissionIds = new ArrayList<>();
        Set<Permission> permissions = permissionDao.findById(id);
        for (Permission permission : permissions) {
            permissionIds.add(permission.getId());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("permissionList",permissionList);
        map.put("permissionIds",permissionIds);

        return map;
    }

    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        if(queryString != null && queryString.length()>0){
            queryString = queryString.replaceAll(" ","");
        }

        PageHelper.startPage(currentPage,pageSize);
        Page<Permission> page =  permissionDao.findCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }
}
